<template>
  <el-dialog
    title="批量设置考核组成"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="1200px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="batch-set-content">
      <!-- 左侧：考核组成设置 -->
      <div class="left-panel">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>考核组成设置</span>
              <el-button type="primary" size="small" @click="addExamPart">
                <el-icon><Plus /></el-icon> 添加考核组成
              </el-button>
            </div>
          </template>
          
          <el-alert
            v-if="examPartTemplates.length === 0"
            title="请添加考核组成部分"
            type="info"
            :closable="false"
            show-icon
          />
          
          <el-table
            v-if="examPartTemplates.length > 0"
            :data="examPartTemplates"
            border
            style="width: 100%; margin-bottom: 20px;"
          >
            <el-table-column prop="name" label="考核部分名称" min-width="120" />
            <el-table-column prop="proportion" label="比例%" width="80">
              <template #default="scope">
                <span>{{ scope.row.proportion }}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="scoreTypeName" label="评分类型" width="120" />
            <el-table-column label="考核性质" width="180">
              <template #default="scope">
                <el-tag 
                  v-if="scope.row.examPartType === 'FORMATIVE'" 
                  type="success" 
                  size="small" 
                  effect="plain" 
                  style="margin-right: 5px;"
                >
                  形成性
                </el-tag>
                <el-tag 
                  v-if="scope.row.examPartType === 'FINAL'" 
                  type="warning" 
                  size="small" 
                  effect="plain"
                >
                  终结性
                </el-tag>
                <el-tag 
                  v-if="scope.row.examPartType === 'OTHER'" 
                  type="info" 
                  size="small" 
                  effect="plain"
                >
                  其它
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="160" fixed="right">
              <template #default="scope">
                <el-button type="primary" size="small" @click="editExamPart(scope.$index)">
                  <el-icon><Edit /></el-icon> 编辑
                </el-button>
                <el-button type="danger" size="small" @click="removeExamPart(scope.$index)">
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="total-proportion" v-if="examPartTemplates.length > 0">
            <el-progress 
              :percentage="totalProportion" 
              :status="totalProportion === 100 ? 'success' : ''" 
              :stroke-width="20"
              :format="(percentage) => `总比例: ${percentage}%`"
            />
          </div>
        </el-card>
      </div>
      
      <!-- 右侧：教学任务选择 -->
      <div class="right-panel">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>选择目标教学任务</span>
              <div class="header-actions">
                <el-checkbox 
                  v-model="selectAll" 
                  :indeterminate="isIndeterminate"
                  @change="handleSelectAll"
                  :disabled="teachingMissions.filter(m => !m.hasScores).length === 0"
                >
                  全选可用任务
                </el-checkbox>
                <span class="selected-count">
                  已选择 {{ selectedMissions.length }} / {{ teachingMissions.filter(m => !m.hasScores).length }} 个
                </span>
              </div>
            </div>
          </template>
          
          <!-- 过滤器 -->
          <div class="filters" style="margin-bottom: 20px;">
            <el-form :inline="true" size="small">
              <el-form-item label="课程">
                <el-select 
                  v-model="filterCourseId" 
                  placeholder="选择课程" 
                  style="width: 300px"
                  @change="loadTeachingMissions"
                >
                  <el-option label="全部课程" value="" />
                  <el-option 
                    v-for="course in courses" 
                    :key="course.id" 
                    :label="`${course.name} (${course.code})`" 
                    :value="course.id"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          
          <div v-loading="loadingMissions">
            <el-alert
              v-if="teachingMissions.length === 0 && !loadingMissions"
              title="没有找到符合条件的教学任务"
              type="info"
              :closable="false"
              show-icon
            />
            
            <el-alert
              v-if="teachingMissions.length > 0 && teachingMissions.filter(m => !m.hasScores).length === 0"
              title="当前学期所有任务都已录入成绩，无法批量设置考核组成"
              type="warning"
              :closable="false"
              show-icon
              style="margin-bottom: 16px;"
            />

            <div 
              v-if="teachingMissions.length > 0 && teachingMissions.filter(m => !m.hasScores).length > 0" 
              class="usage-tip"
            >
              <el-icon><InfoFilled /></el-icon>
              <span>点击任务卡片或勾选框选择任务，已录入成绩的任务无法修改考核组成</span>
            </div>

            <el-checkbox-group v-model="selectedMissions" v-if="teachingMissions.length > 0">
              <div class="missions-grid">
                <div 
                  v-for="mission in teachingMissions" 
                  :key="mission.id"
                  class="mission-card-wrapper"
                  :class="{ 
                    'selected': selectedMissions.includes(mission.id),
                    'disabled': mission.hasScores 
                  }"
                  @click="!mission.hasScores && toggleMissionSelection(mission.id)"
                >
                  <el-card 
                    class="mission-card"
                    shadow="hover"
                    :body-style="{ padding: '16px' }"
                  >
                    <div class="mission-content">
                      <div class="mission-checkbox">
                        <el-checkbox 
                          :value="mission.id"
                          :disabled="mission.hasScores"
                          @change="(checked) => handleMissionSelect(mission.id, checked)"
                          @click.stop
                        />
                      </div>
                      <div class="mission-info">
                        <div class="mission-header">
                          <h4 class="mission-title">{{ mission.courseName }}</h4>
                          <div class="mission-status">
                            <el-tag 
                              v-if="mission.hasExamParts" 
                              type="warning" 
                              size="small"
                              effect="plain"
                            >
                              已设置
                            </el-tag>
                            <el-tag 
                              v-if="mission.hasScores" 
                              type="danger" 
                              size="small"
                              effect="plain"
                            >
                              已录入成绩
                            </el-tag>
                          </div>
                        </div>
                        <div class="mission-details">
                          <div class="detail-row">
                            <span class="detail-label">课程编码：</span>
                            <span class="detail-value">{{ mission.courseCode }}</span>
                          </div>
                          <div class="detail-row">
                            <span class="detail-label">教学班：</span>
                            <span class="detail-value">{{ mission.classNames?.join(', ') || '未分配' }}</span>
                          </div>
                          <div class="detail-row">
                            <span class="detail-label">学生人数：</span>
                            <span class="detail-value">{{ mission.studentCount || 0 }}人</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </div>
              </div>
            </el-checkbox-group>
          </div>
        </el-card>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleBatchSet"
          :disabled="examPartTemplates.length === 0 || totalProportion !== 100 || selectedMissions.length === 0"
          :loading="submitting"
        >
          批量设置
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 考核组成编辑对话框 -->
  <ExamPartFormDialog
    v-model:visible="examPartFormVisible"
    :exam-part="currentExamPart"
    :score-types="scoreTypes"
    @submit="handleExamPartSubmit"
  />
</template>

<script>
import { ref, reactive, computed, onMounted, watch, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, InfoFilled } from '@element-plus/icons-vue'
import { courseExamPartApi } from '@/api/course-exam-part'
import { teachingMissionApi } from '@/api/teaching-mission'
import { termApi, courseApi, scoreTypeApi } from '@/api/base-data'
import ExamPartFormDialog from './ExamPartFormDialog.vue'

export default {
  name: 'BatchSetExamPartsDialog',
  components: {
    Plus,
    Edit,
    Delete,
    InfoFilled,
    ExamPartFormDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    termId: {
      type: Number,
      default: null
    }
  },
  emits: ['update:visible', 'completed'],
  setup(props, { emit }) {
    const { visible, termId } = toRefs(props)
    const examPartTemplates = ref([])
    const selectedMissions = ref([])
    const teachingMissions = ref([])
    const terms = ref([])
    const courses = ref([])
    const scoreTypes = ref([])
    
    const loadingMissions = ref(false)
    const submitting = ref(false)
    
    const filterTermId = ref('')
    const filterCourseId = ref('')
    
    // 考核组成编辑相关
    const examPartFormVisible = ref(false)
    const currentExamPart = ref(null)
    const editingIndex = ref(-1)
    
    // 计算属性
    const totalProportion = computed(() => {
      return examPartTemplates.value.reduce((sum, part) => sum + (part.proportion || 0), 0)
    })
    
    const selectAll = computed({
      get: () => {
        const availableMissions = teachingMissions.value.filter(m => !m.hasScores)
        return availableMissions.length > 0 && selectedMissions.value.length === availableMissions.length
      },
      set: (value) => {
        const availableMissions = teachingMissions.value.filter(m => !m.hasScores)
        if (value) {
          selectedMissions.value = availableMissions.map(m => m.id)
        } else {
          selectedMissions.value = []
        }
      }
    })
    
    const isIndeterminate = computed(() => {
      const availableMissions = teachingMissions.value.filter(m => !m.hasScores)
      const selected = selectedMissions.value.length
      const total = availableMissions.length
      return selected > 0 && selected < total
    })
    
    // 方法
    const loadBasicData = async () => {
      try {
        const [termsData, coursesData, scoreTypesData] = await Promise.all([
          termApi.getAllTerms(),
          courseApi.getAllCourses(),
          scoreTypeApi.getAllScoreTypes()
        ])
        
        terms.value = termsData
        courses.value = coursesData
        scoreTypes.value = scoreTypesData
        
        // 如果指定了termId，则设置为该学期，否则设置为当前学期
        if (termId.value) {
          filterTermId.value = termId.value
        } else {
          const currentTerm = terms.value.find(term => term.isCurrent)
          if (currentTerm) {
            filterTermId.value = currentTerm.id
          }
        }
      } catch (error) {
        console.error('加载基础数据失败:', error)
        ElMessage.error('加载基础数据失败')
      }
    }
    
    const loadTeachingMissions = async () => {
      loadingMissions.value = true
      try {
        const params = {}
        
        // 如果指定了termId，则只查询该学期的任务
        const targetTermId = termId.value || filterTermId.value
        if (targetTermId) params.termId = targetTermId
        if (filterCourseId.value && filterCourseId.value !== '') params.courseId = filterCourseId.value
        
        const data = await teachingMissionApi.getAllTeachingMissionsList()
        
        // 前端过滤
        let filteredData = data
        if (targetTermId) {
          filteredData = filteredData.filter(m => m.termId === targetTermId)
        }
        if (filterCourseId.value && filterCourseId.value !== '') {
          filteredData = filteredData.filter(m => m.courseId === filterCourseId.value)
        }
        
        teachingMissions.value = filteredData
        selectedMissions.value = []
      } catch (error) {
        console.error('加载教学任务失败:', error)
        ElMessage.error('加载教学任务失败')
      } finally {
        loadingMissions.value = false
      }
    }
    
    const addExamPart = () => {
      currentExamPart.value = {
        name: '',
        proportion: 0,
        examPartType: 'OTHER',
        scoreTypeId: null
      }
      editingIndex.value = -1
      examPartFormVisible.value = true
    }
    
    const editExamPart = (index) => {
      currentExamPart.value = { ...examPartTemplates.value[index] }
      editingIndex.value = index
      examPartFormVisible.value = true
    }
    
    const removeExamPart = (index) => {
      examPartTemplates.value.splice(index, 1)
    }
    
    const handleExamPartSubmit = (examPart) => {
      // 设置评分类型名称
      if (examPart.scoreTypeId) {
        const scoreType = scoreTypes.value.find(st => st.id === examPart.scoreTypeId)
        examPart.scoreTypeName = scoreType ? scoreType.name : ''
      }
      
      if (editingIndex.value >= 0) {
        // 编辑模式
        examPartTemplates.value[editingIndex.value] = { ...examPart }
      } else {
        // 新增模式
        examPartTemplates.value.push({ ...examPart })
      }
      
      examPartFormVisible.value = false
    }
    
    const handleSelectAll = (value) => {
      selectAll.value = value
    }

    const handleMissionSelect = (missionId, checked) => {
      if (checked) {
        if (!selectedMissions.value.includes(missionId)) {
          selectedMissions.value.push(missionId)
        }
      } else {
        const index = selectedMissions.value.indexOf(missionId)
        if (index > -1) {
          selectedMissions.value.splice(index, 1)
        }
      }
    }

    const toggleMissionSelection = (missionId) => {
      const isSelected = selectedMissions.value.includes(missionId)
      handleMissionSelect(missionId, !isSelected)
    }
    
    const handleBatchSet = async () => {
      if (examPartTemplates.value.length === 0) {
        ElMessage.warning('请先添加考核组成部分')
        return
      }
      
      if (totalProportion.value !== 100) {
        ElMessage.warning('考核组成总比例必须为100%')
        return
      }
      
      if (selectedMissions.value.length === 0) {
        ElMessage.warning('请选择目标教学任务')
        return
      }
      
      // 检查是否有已录入成绩的任务
      const selectedMissionData = teachingMissions.value.filter(m => selectedMissions.value.includes(m.id))
      const missionsWithScores = selectedMissionData.filter(m => m.hasScores)
      
      if (missionsWithScores.length > 0) {
        ElMessage.error(`以下任务已录入成绩，无法调整考核组成设置：${missionsWithScores.map(m => m.courseName).join(', ')}`)
        return
      }
      
      try {
        await ElMessageBox.confirm(
          `确定要为选中的 ${selectedMissions.value.length} 个教学任务批量设置考核组成吗？`,
          '确认批量设置',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        submitting.value = true
        
        await courseExamPartApi.batchSetExamParts(examPartTemplates.value, selectedMissions.value)
        
        ElMessage.success('批量设置考核组成成功')
        emit('completed')
        handleClose()
        
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量设置失败:', error)
          ElMessage.error('批量设置失败')
        }
      } finally {
        submitting.value = false
      }
    }
    
    const handleClose = () => {
      emit('update:visible', false)
      // 重置数据
      examPartTemplates.value = []
      selectedMissions.value = []
      teachingMissions.value = []
      filterTermId.value = ''
      filterCourseId.value = ''
    }
    
    // 监听器
    watch(() => visible.value, (newValue) => {
      if (newValue) {
        loadBasicData()
        loadTeachingMissions()
      }
    })
    
    return {
      visible,
      termId,
      examPartTemplates,
      selectedMissions,
      teachingMissions,
      terms,
      courses,
      scoreTypes,
      loadingMissions,
      submitting,
      filterTermId,
      filterCourseId,
      examPartFormVisible,
      currentExamPart,
      totalProportion,
      selectAll,
      isIndeterminate,
      
      addExamPart,
      editExamPart,
      removeExamPart,
      handleExamPartSubmit,
      handleSelectAll,
      handleMissionSelect,
      toggleMissionSelection,
      handleBatchSet,
      handleClose,
      loadTeachingMissions
    }
  }
}
</script>

<style scoped>
.batch-set-content {
  display: flex;
  gap: 20px;
  height: 600px;
}

.left-panel {
  flex: 1;
  min-width: 500px;
}

.right-panel {
  flex: 1;
  min-width: 500px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.selected-count {
  font-size: 14px;
  color: #909399;
}

.total-proportion {
  margin-top: 15px;
}

.filters {
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.missions-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
  padding: 4px;
}

.mission-card-wrapper {
  transition: all 0.3s ease;
}

.mission-card-wrapper.selected .mission-card {
  border-color: #409eff;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.3);
}

.mission-card-wrapper.disabled .mission-card {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  opacity: 0.7;
  cursor: not-allowed;
}

.mission-card {
  border: 2px solid #dcdfe6;
  transition: all 0.3s ease;
  cursor: pointer;
}

.mission-card:hover {
  border-color: #c6e2ff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.mission-card-wrapper.disabled .mission-card:hover {
  border-color: #e4e7ed;
  box-shadow: none;
}

.usage-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
  font-size: 13px;
  color: #409eff;
  margin-bottom: 16px;
}

.mission-content {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.mission-checkbox {
  flex-shrink: 0;
  padding-top: 2px;
}

.mission-info {
  flex: 1;
  min-width: 0;
}

.mission-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
  gap: 12px;
}

.mission-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  line-height: 1.4;
  flex: 1;
  min-width: 0;
  word-break: break-word;
}

.mission-status {
  display: flex;
  gap: 6px;
  flex-shrink: 0;
}

.mission-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-row {
  display: flex;
  align-items: center;
  font-size: 14px;
  line-height: 1.4;
}

.detail-label {
  color: #909399;
  font-weight: 500;
  min-width: 80px;
  flex-shrink: 0;
}

.detail-value {
  color: #606266;
  flex: 1;
  word-break: break-word;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
